<template>
  <el-form :model="formModel" :rules="rules" ref="form" size="large" autocomplete="off">
    <el-form-item>
      <h2>注册</h2>
    </el-form-item>
    <el-form-item prop="username">
      <el-input v-model="formModel.username" :prefix-icon="User" placeholder="请输入用户名"></el-input>
    </el-form-item>
    <el-form-item prop="password">
      <el-input v-model="formModel.password" :prefix-icon="Lock" type="password" placeholder="请输入密码"></el-input>
    </el-form-item>
    <el-form-item prop="repassword">
      <el-input v-model="formModel.repassword" :prefix-icon="Lock" type="password" placeholder="请再次输入密码"></el-input>
    </el-form-item>
    <!-- 新增邮箱 -->
    <el-form-item prop="email">
      <el-input v-model="formModel.email" placeholder="请输入邮箱" />
    </el-form-item>
    <el-form-item prop="role">
      <el-select v-model="formModel.role" placeholder="请选择角色">
        <el-option label="买家" value="buyer"></el-option>
        <el-option label="卖家" value="seller"></el-option>
        <el-option label="管理员" value="admin"></el-option>
      </el-select>
    </el-form-item>
    <el-form-item>
      <el-button class="button" @click="register" type="danger" auto-insert-space>注册</el-button>
    </el-form-item>
    <el-form-item class="flex">
      <el-link type="info" :underline="false" @click="$emit('close')">取消</el-link>
    </el-form-item>
  </el-form>
</template>

<script setup>
import { ref } from 'vue';
import { ElMessage } from 'element-plus';
import { User, Lock } from '@element-plus/icons-vue';
import axios from 'axios';

const emit = defineEmits(['close']);

const form = ref();
const formModel = ref({
  username: '',
  password: '',
  repassword: '',
  email: '',
  role: ''
});

// 验证规则扩展
const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 5, max: 10, message: '用户名必须是5-10位字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { pattern: /^\S{6,15}$/, message: '密码必须是6-15位非空字符', trigger: 'blur' }
  ],
  repassword: [
    { required: true, message: '请再次输入密码', trigger: 'blur' },
    { pattern: /^\S{6,15}$/, message: '密码必须是6-15位非空字符', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== formModel.value.password) {
          callback(new Error('两次输入密码不一致'));
        } else {
          callback();
        }
      },
      trigger: 'blur'
    }
  ],
  // 新增邮箱校验
  email: [
    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
    { type: 'email', message: '邮箱格式不正确', trigger: ['blur', 'change'] }
  ],
  role: [{ required: true, message: '请选择角色', trigger: 'change' }]
};

const register = async () => {
  await form.value.validate();

  try {
    const response = await axios.get(`http://localhost:3000/users?username=${formModel.value.username}`);
    if (response.data.length > 0) {
      return ElMessage.error('用户名已存在');
    }

    const newUser = {
      username: formModel.value.username,
      password: formModel.value.password,
      email: formModel.value.email,
      role: formModel.value.role,
      registeredAt: new Date().toISOString().split('T')[0] // 当前日期 YYYY-MM-DD
    };

    await axios.post('http://localhost:3000/users', newUser);

    ElMessage.success('注册成功');
    emit('close'); // 关闭对话框
  } catch (error) {
    ElMessage.error('注册失败，请稍后再试');
    console.error(error);
  }
};
</script>

<style scoped>
.el-form {
  padding-top: 40px;
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
  width: 100%;
}

.el-form-item {
  width: 100%;
  margin-bottom: 20px;
}

.el-form-item:last-child {
  margin-bottom: 0;
}

.el-input {
  width: 100%;
}

.el-button {
  width: 100%;
}

.flex {
  width: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.el-checkbox {
  margin-right: 10px;
}

h2 {
  margin: 0 auto;
}
</style>